package com.bigdata.service.controller.app;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaIgnore;
import com.amazonaws.util.Md5Utils;
import com.bigdata.common.annotation.Log;
import com.bigdata.common.annotation.RepeatSubmit;
import com.bigdata.common.constant.CacheConstants;
import com.bigdata.common.core.controller.BaseController;
import com.bigdata.common.core.domain.PageQuery;
import com.bigdata.common.core.domain.R;
import com.bigdata.common.core.page.TableDataInfo;
import com.bigdata.common.core.validate.AddGroup;
import com.bigdata.common.core.validate.EditGroup;
import com.bigdata.common.enums.BusinessType;
import com.bigdata.common.utils.CaptchaUtil;
import com.bigdata.common.utils.StringUtils;
import com.bigdata.common.utils.poi.ExcelUtil;
import com.bigdata.common.utils.redis.RedisUtils;
import com.bigdata.service.domain.bo.PwdBo;
import com.bigdata.service.domain.bo.ServiceUsersBo;
import com.bigdata.service.domain.vo.ServiceUsersVo;
import com.bigdata.service.service.IServiceUsersService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 用户信息
 *
 * @author ruoyi
 * @date 2025-07-15
 */
@Validated
@RequiredArgsConstructor
@RestController
@Slf4j
@RequestMapping("/app/service/users")
public class AppServiceUsersController extends BaseController {

    private final IServiceUsersService iServiceUsersService;

    /**
     * 修改用户信息
     */
    @RepeatSubmit()
    @PostMapping("/updatePwd")
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody PwdBo bo) {

        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.defaultString(bo.getUuid(), "");
        String captcha = RedisUtils.getCacheObject(verifyKey);
        RedisUtils.deleteObject(verifyKey);
        if (StringUtils.isBlank(captcha)) {
            throw new RuntimeException("验证码已过期");
        }
        if (!bo.getCode().equalsIgnoreCase(captcha)) {
            throw new RuntimeException("验证码错误");
        }
        ServiceUsersBo usersBo = new ServiceUsersBo();
        usersBo.setUserId(getUserId());
        ServiceUsersVo serviceUsersVo = iServiceUsersService.queryById(getUserId());
//        String pwd = Md5Utils.md5AsBase64(password.getBytes());
        if(!serviceUsersVo.getPasswordHash().equals(Md5Utils.md5AsBase64(bo.getOldPwd().getBytes()) )) {
            throw new RuntimeException("旧密码错误");
        }
        usersBo.setPasswordHash(Md5Utils.md5AsBase64(bo.getNewPwd().getBytes()));
        return toAjax(iServiceUsersService.updateByBo(usersBo));
    }

    /**
     * 获取验证码图片
     */
    @SaIgnore
    @GetMapping("/captcha")
    public ResponseEntity<byte[]> getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 生成验证码文本
        String captchaText = CaptchaUtil.generateCaptchaText();

        // 获取sessionId
        // 生成唯一key
        String captchaKey = UUID.randomUUID().toString();

        log.info("session :{}", captchaKey);

        // 存储验证码（包含过期时间）
        CaptchaUtil.storeCaptcha(captchaKey, captchaText);

        // 生成验证码图片
        byte[] imageBytes = CaptchaUtil.generateCaptchaImage(captchaText);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Captcha-Key", captchaKey);
        headers.set("content-Key", captchaKey);
        headers.set("Access-Control-Expose-Headers", "Captcha-Key");
//        headers.set("Access-Control-Expose-Headers", "content-Key");
        // 将key通过响应头返回给前端
        response.setHeader("Captcha1-Key", captchaKey);
        return ResponseEntity.ok()
            .contentType(MediaType.IMAGE_PNG).headers(headers)
            .body(imageBytes);
    }


    @PostMapping("/updateUser")
    public R<Void> updateUser(@RequestBody ServiceUsersBo bo) {
        bo.setUserId(getUserId());
        return toAjax(iServiceUsersService.updateByBo(bo));
    }

}
